'use strict';
const db = uniCloud.database();
const roomsCollection = db.collection('rooms');

exports.main = async (event, context) => {
	const { room_id, room_number, price, room_type, images, furniture_list, introduction, token } = event;
	
	// 只检查token是否存在
	if (!token) {
		return {
			code: 401,
			message: '未登录'
		};
	}
	
	// 参数校验
	if (!room_id) {
		return {
			code: 1,
			message: '缺少房间ID参数'
		};
	}
	
	if (!room_number) {
		return {
			code: 2,
			message: '缺少房间号参数'
		};
	}
	
	if (!price || typeof price !== 'number' || price < 0) {
		return {
			code: 3,
			message: '价格参数无效，应为非负数'
		};
	}
	
	if (!room_type) {
		return {
			code: 4,
			message: '缺少户型参数'
		};
	}
	
	// 更新房间信息
	const updateData = {
		room_number: room_number,
		price: price,
		room_type: room_type,
		update_time: new Date()
	};
	
	// 如果有传图片数组，则更新
	if (images && Array.isArray(images)) {
		updateData.images = images;
	}
	
	// 如果有传家具列表，则更新
	if (furniture_list && Array.isArray(furniture_list)) {
		updateData.furniture_list = furniture_list;
	}
	
	// 如果有传简介，则更新
	if (introduction !== undefined) {
		updateData.introduction = introduction;
	}
	
	try {
		const updateResult = await roomsCollection.doc(room_id).update(updateData);
		
		if (updateResult.updated === 0) {
			return {
				code: 5,
				message: '房间不存在或信息更新失败'
			};
		}
		
		return {
			code: 0,
			message: '房间信息更新成功'
		};
	} catch (e) {
		console.error(e);
		return {
			code: 500,
			message: '服务器错误：' + e.message
		};
	}
}; 